package quickstart.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Transactional;

import quickstart.model.User;

@Transactional
public class UserServiceImpl implements UserService {
    private EntityManager em;

    @PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    @SuppressWarnings("unchecked")
    public List<User> findAll() {
        Query query = getEntityManager().createQuery("select u FROM User u");
        return query.getResultList();
    }

    private void save(User user) {
        if (user.getId() == null) {
            // new
            em.persist(user);
        } else {
            // update
            em.merge(user);
        }
    }

    public void remove(int id) {
        User user = find(id);
        if (user != null) {
            em.remove(user);
        }
    }

    private EntityManager getEntityManager() {
        return em;
    }

    public User find(int id) {
        return em.find(User.class, id);
    }

    public void register(User user) {
        this.save(user);        
    }

    public void update(User user) {
        this.save(user);        
    }

}
